package com.robotic.sensor.controller;

import com.robotic.common.annotation.Log;
import com.robotic.common.core.controller.BaseController;
import com.robotic.common.core.domain.AjaxResult;
import com.robotic.common.core.page.TableDataInfo;
import com.robotic.common.enums.BusinessType;
import com.robotic.sensor.domain.SensorData;
import com.robotic.sensor.service.TemperatureSensorService;
import com.robotic.sensor.service.ModbusRTUService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;

/**
 * 温度传感器控制器
 * 提供温度传感器管理和数据读取的REST API接口
 */
@RestController
@RequestMapping("/sensor/temperature")
public class TemperatureSensorController extends BaseController {
    
    @Autowired
    private TemperatureSensorService temperatureSensorService;
    
    @Autowired
    private ModbusRTUService modbusRTUService;
    
    /**
     * 连接温度传感器串口
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:connect')")
    @Log(title = "温度传感器", businessType = BusinessType.OTHER)
    @PostMapping("/connect")
    public AjaxResult connect(@RequestParam String portName) {
        try {
            boolean success = modbusRTUService.connect(portName);
            if (success) {
                return AjaxResult.success("串口连接成功: " + portName);
            } else {
                return AjaxResult.error("串口连接失败: " + portName);
            }
        } catch (Exception e) {
            return AjaxResult.error("连接异常: " + e.getMessage());
        }
    }
    
    /**
     * 断开温度传感器串口连接
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:disconnect')")
    @Log(title = "温度传感器", businessType = BusinessType.OTHER)
    @PostMapping("/disconnect")
    public AjaxResult disconnect() {
        try {
            modbusRTUService.disconnect();
            return AjaxResult.success("串口连接已断开");
        } catch (Exception e) {
            return AjaxResult.error("断开连接异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取串口连接状态
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:status')")
    @GetMapping("/status")
    public AjaxResult getConnectionStatus() {
        boolean connected = modbusRTUService.isConnected();
        return AjaxResult.success().put("connected", connected);
    }
    
    /**
     * 读取单个温度传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:read')")
    @Log(title = "温度传感器", businessType = BusinessType.OTHER)
    @GetMapping("/read")
    public AjaxResult readTemperatureData(
            @RequestParam int deviceId,
            @RequestParam(required = false) Long robotId,
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) BigDecimal x,
            @RequestParam(required = false) BigDecimal y) {
        try {
            SensorData sensorData = temperatureSensorService.readTemperatureData(
                    deviceId, robotId, taskId, x, y);
            
            if (sensorData != null) {
                return AjaxResult.success("温度数据读取成功", sensorData);
            } else {
                return AjaxResult.error("温度数据读取失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("读取温度数据异常: " + e.getMessage());
        }
    }
    
    /**
     * 批量读取多个温度传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:read')")
    @Log(title = "温度传感器", businessType = BusinessType.OTHER)
    @PostMapping("/read/batch")
    public AjaxResult readMultipleTemperatureData(@RequestBody TemperatureReadRequest request) {
        try {
            List<SensorData> sensorDataList = temperatureSensorService.readMultipleTemperatureData(
                    request.getDeviceIds(), request.getRobotId(), request.getTaskId(), 
                    request.getX(), request.getY());
            
            return AjaxResult.success("批量温度数据读取完成", sensorDataList);
        } catch (Exception e) {
            return AjaxResult.error("批量读取温度数据异常: " + e.getMessage());
        }
    }
    
    /**
     * 处理并保存温度传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:process')")
    @Log(title = "温度传感器", businessType = BusinessType.INSERT)
    @PostMapping("/process")
    public AjaxResult processTemperatureData(
            @RequestParam int deviceId,
            @RequestParam(required = false) Long robotId,
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) BigDecimal x,
            @RequestParam(required = false) BigDecimal y) {
        try {
            boolean success = temperatureSensorService.processAndSaveTemperatureData(
                    deviceId, robotId, taskId, x, y);
            
            if (success) {
                return AjaxResult.success("温度数据处理成功");
            } else {
                return AjaxResult.error("温度数据处理失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("处理温度数据异常: " + e.getMessage());
        }
    }
    
    /**
     * 读取设备信息
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:info')")
    @GetMapping("/info")
    public AjaxResult getDeviceInfo(@RequestParam int deviceId) {
        try {
            TemperatureSensorService.TemperatureSensorInfo info = 
                    temperatureSensorService.readDeviceInfo(deviceId);
            
            if (info != null) {
                return AjaxResult.success("设备信息读取成功", info);
            } else {
                return AjaxResult.error("设备信息读取失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("读取设备信息异常: " + e.getMessage());
        }
    }
    
    /**
     * 设置发射率
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:config')")
    @Log(title = "温度传感器", businessType = BusinessType.UPDATE)
    @PostMapping("/emission-rate")
    public AjaxResult setEmissionRate(
            @RequestParam int deviceId,
            @RequestParam BigDecimal emissionRate) {
        try {
            // 验证发射率范围（0.001-1.200）
            if (emissionRate.compareTo(BigDecimal.valueOf(0.001)) < 0 || 
                emissionRate.compareTo(BigDecimal.valueOf(1.200)) > 0) {
                return AjaxResult.error("发射率必须在0.001-1.200范围内");
            }
            
            boolean success = temperatureSensorService.setEmissionRate(deviceId, emissionRate);
            
            if (success) {
                return AjaxResult.success("发射率设置成功");
            } else {
                return AjaxResult.error("发射率设置失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("设置发射率异常: " + e.getMessage());
        }
    }
    
    /**
     * 测试温度传感器连接
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:test')")
    @GetMapping("/test")
    public AjaxResult testConnection(@RequestParam int deviceId) {
        try {
            TemperatureSensorService.TemperatureSensorInfo info = 
                    temperatureSensorService.readDeviceInfo(deviceId);
            
            if (info != null && info.getDeviceId() != null) {
                return AjaxResult.success("设备连接正常", info);
            } else {
                return AjaxResult.error("设备连接失败或设备不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("测试连接异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取支持的串口列表
     */
    @PreAuthorize("@ss.hasPermi('sensor:temperature:ports')")
    @GetMapping("/ports")
    public AjaxResult getAvailablePorts() {
        try {
            // 这里可以实现获取系统可用串口的逻辑
            List<String> ports = new ArrayList<>();
            // Windows系统常见串口
            for (int i = 1; i <= 20; i++) {
                ports.add("COM" + i);
            }
            
            return AjaxResult.success("可用串口列表", ports);
        } catch (Exception e) {
            return AjaxResult.error("获取串口列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 温度传感器批量读取请求对象
     */
    public static class TemperatureReadRequest {
        private List<Integer> deviceIds;
        private Long robotId;
        private Long taskId;
        private BigDecimal x;
        private BigDecimal y;
        
        // Getters and Setters
        public List<Integer> getDeviceIds() {
            return deviceIds;
        }
        
        public void setDeviceIds(List<Integer> deviceIds) {
            this.deviceIds = deviceIds;
        }
        
        public Long getRobotId() {
            return robotId;
        }
        
        public void setRobotId(Long robotId) {
            this.robotId = robotId;
        }
        
        public Long getTaskId() {
            return taskId;
        }
        
        public void setTaskId(Long taskId) {
            this.taskId = taskId;
        }
        
        public BigDecimal getX() {
            return x;
        }
        
        public void setX(BigDecimal x) {
            this.x = x;
        }
        
        public BigDecimal getY() {
            return y;
        }
        
        public void setY(BigDecimal y) {
            this.y = y;
        }
    }
}